package com.ld.security.server.user.modules.ups.util;

import com.ld.security.auth.shiro.util.LoginUtil;
import com.ld.security.common.core.util.StringUtil;
import com.ld.security.common.tomcat.util.SessionUtil;
import com.ld.security.server.user.modules.ups.entity.UpsActionEntity;
import com.ld.security.server.user.modules.ups.entity.UpsUserEntity;
import com.ld.security.server.user.modules.ups.service.IUpsActionService;
import com.ld.security.server.user.modules.ups.service.IUpsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
public class UpsUtil {

    private static IUpsUserService iUpsUserService;


    private static  IUpsActionService iUpsActionService;

    /**
     * 异步保存用户的行为
     * @param actionEntity
     */
    public static void saveAction(UpsActionEntity actionEntity){
        if(StringUtil.isNull( actionEntity.getUpsUserId())){
            actionEntity.setUpsUserId(getUpsUser().getId());
        }
        CompletableFuture.runAsync(() -> {
            iUpsActionService.save(actionEntity);
        });
    }

  public static String getUpsUserId() {
        return getUpsUser().getId();
  }
        /**
         * 得到用户画像
         * @return
         */
    public static UpsUserEntity getUpsUser(){
        UpsUserEntity ups  = null;
        if(LoginUtil.isLogin()){
//            String userId =  LoginUtil.getUserId();
//             ups =   iUpsUserService.getByUserId(userId);
            String ip = SessionUtil.getIPAddress();
            ups= iUpsUserService.getByIp(ip);
        }else{
           String ip = SessionUtil.getIPAddress();
            ups= iUpsUserService.getByIp(ip);
        }
        if(ups == null){
            //防止并发创建多个用户
            synchronized (UpsUtil.class){
                ups = newUpsUser();
                iUpsUserService.save(ups);
            }

        }
        return ups;

    }

    public static UpsUserEntity newUpsUser(){
        UpsUserEntity ups = new UpsUserEntity();
        String ip = SessionUtil.getIPAddress();
        ups.setIp(ip);
        ups.setSysUserId("-1");
        ups.setCity( SessionUtil.getCity());
        String label = ip;
        if(LoginUtil.isLogin()){
            label =  LoginUtil.getUsername();
            String userId =  LoginUtil.getUserId();
            ups.setSysUserId(userId);
        }
        ups.setLabel(label);
        return ups;
    }


    @Autowired
    public void setiUpsUserService(IUpsUserService iUpsUserService) {
        UpsUtil.iUpsUserService = iUpsUserService;
    }
    @Autowired
    public void setiUpsActionService(IUpsActionService iUpsActionService) {
        UpsUtil.iUpsActionService = iUpsActionService;
    }
}
